<template>
	<view>
		<view>
			<u-steps :list=" stepsTop " :current=" activeTop "></u-steps>
			<view class='teach'>
				<image src='/static/icons/route.png' />
				<view class=''>第一步，输入家庭WiFi信息</view>
				<view class=''>第二步，连接设备热点</view>
				<view class=''>第三步，重新连接家庭WiFi</view>
			</view>
			<br />
			<br />
			<block v-if='activeTop === 0'>
				<view class='form'>
					<view class='title'>
						输入家庭WiFi信息
					</view>
					<label class='account'>
						<image class='icon' src='/static/icons/wifi.png' />
						<input type='text' @input='inputAcc' :value=' ssid ' placeholder='请输入WiFi名称' />
					</label>
					<label class='password'>
						<image class='icon' src='/static/icons/pwd.png' />
						<input v-if='pwdHide === true ' @input='inputPwd' :value='password' type='password'
							placeholder='请输入密码' />
						<input v-if=' pwdHide === false ' @input='inputPwd' :value=' password ' type='text'
							placeholder='请输入密码' />
						<view class='icon' @click='lookPwd'>
							<image v-if=' pwdHide === true ' class='icon' src='/static/icons/close.png' />
							<image v-if=' pwdHide === false ' class='icon' src='/static/icons/open.png' />
						</view>
					</label>
					<view class='btn'>
						<u-button type="primary" :ripple="true" ripple-bg-color="#2f20f6" shape="circle"
							@click='onConfirm'>
							下一步
						</u-button>
					</view>
				</view>
			</block>
			<block v-if=' activeTop === 1 '>
				<view class='form'>
					<view class='title'>
						连接设备热点
					</view>
					<label class='account'>
						<image class='icon' src='/static/icons/acc.png' />
						<input type='text' disabled @input='inputDeviceSSID' :value=' deviceSSID '
							placeholder='请输入设备热点名称' />
					</label>
					<label class='password'>
						<image class='icon' src='/static/icons/pwd.png' />
						<input v-if=' pwdHide === true ' disabled @input='inputDevicePWD' :value=' devicePWD '
							type='password' placeholder='请输入密码' />
						<input v-if=' pwdHide === false ' disabled @input='inputDevicePWD' :value=' devicePWD '
							type='text' placeholder='请输入密码' />
						<view class='icon' @click='lookPwd'>
							<image v-if=' pwdHide === true ' class='icon' src='/static/icons/close.png' />
							<image v-if=' pwdHide === false ' class='icon' src='/static/icons/open.png' />
						</view>
					</label>
					<view class='btn'>
						<u-button type="primary" :ripple="true" ripple-bg-color="#2f20f6" shape="circle"
							@click='onConnect'>
							连接
						</u-button>
					</view>
				</view>
			</block>
			<block v-if=' activeTop === 2 '>
				<view class='step'>
					<view class='item' v-for=' (item,index) in steps '>
						<u-loading v-if=' item.success === false ' size="48" mode="flower"></u-loading>
						<image v-if=' item.success === true ' src='/static/icons/yes.png' />
						<text class='desc'> {{item.text}} </text>
					</view>
				</view>
				<!-- <button @click='closeUDP'>关闭</button> -->
			</block>
		</view>

	</view>
</template>

<script>
	const {
		request
	} = require('../../services/request.js');

	var timer;
	export default {
		data() {
			return {
				stepsTop: [{
						name: '连接WiFi'
					},
					{
						name: '连接软热点'
					},
					{
						name: '开始配网'
					}
				],
				steps: [{
						text: '手机与设备通信成功',
						success: false
					},
					{
						text: '设备配网成功',
						success: false
					},
					{
						text: '切换回家庭WiFi',
						success: false
					},
					{
						text: '正在创建设备',
						success: false
					},
					{
						text: '绑定成功',
						success: false
					}
				],
				activeTop: 0,
				pwdHide: true,
				ssid: '',
				password: '',
				deviceSSID: 'XiaoYi_IOT_AirBox',
				devicePWD: 'asdqwe9867',
				udp: '',
				port: 0
			}
		},
		async onLoad() {
			this.startWifi();
		},
		onShow() {
			this.getWifiInfo()
		},
		onUnload() {
			//#ifdef MP-WEIXIN
			wx.stopWifi();
			//#endif
		},
		methods: {
			onConfirm() {
				const that = this;
				if ((this.ssid.trim() === '') || (this.password.trim() === '')) {
					uni.showToast({
						title: '请输入完整',
						icon: 'error'
					});
					return;
				}
				that.activeTop += 1;

			},
			lookPwd() {
				this.pwdHide = !this.pwdHide;
			},
			inputPwd(e) {
				this.password = e.detail.value

			},
			inputDevicePWD(e) {
				this.devicePWD = e.detail.value

			},
			inputAcc(e) {
				this.ssid = e.detail.value

			},
			inputDeviceSSID(e) {
				this.deviceSSID = e.detail.value

			},

			onConnect() {
				const that = this;
				uni.showLoading({
					title: '连接中',

				})
				console.log("ssid:", this.deviceSSID, ",password:", this.devicePWD);
				//条件编译
				//#ifdef MP-WEIXIN
				wx.connectWifi({
					SSID: this.deviceSSID,
					password: this.devicePWD,
				}).then((res) => {
					uni.hideLoading();
					console.log('=====', res);
					if (res.wifiMsg === 'target wifi is already connected.') {
						that.activeTop += 1;
						that.udpConnect();
					}
				}).catch((err) => {
					uni.hideLoading();
					uni.showToast({
						title: '连接失败',
						icon: 'error'
					})
					console.error(err);
				});
				wx.onWifiConnected((result) => {
					uni.hideLoading();
					that.activeTop += 1;
					that.udpConnect();
					wx.offWifiConnected((rr) => {
						console.log('关闭设备热点连接的监听')
					});
				})
				//#endif
			},

			startWifi() {
				const that = this;
				//#ifdef MP-WEIXIN
				wx.startWifi({
					success(res) {
						console.log(res.errMsg, 'wifi初始化成功')
						that.getWifiInfo();
					},
					fail: function(err) {
						uni.showToast({
							title: '请连接路由器!',
							duration: 2000,
							icon: 'none'
						})
					}
				})
				//#endif
			},
			getWifiInfo() {
				const that = this;
				//#ifdef MP-WEIXIN
				wx.getConnectedWifi({
					success(res) {
						console.log("getConnectedWifi ok:", JSON.stringify(res))
						if ('getConnectedWifi:ok' === res.errMsg) {

							that.ssid = res.wifi.SSID;
							that.bssid = res.wifi.BSSID;

						} else {
							uni.showToast({
								title: '请连接路由器',
								duration: 2000,
								icon: 'none'
							})
						}
					},
					fail(err) {
						uni.showToast({
							title: '请连接路由器',
							duration: 2000,
							icon: 'none'
						})
					}
				});

				//#endif
			},

			udpConnect() {
				const that = this;
				//#ifdef MP-WEIXIN
				const udp = wx.createUDPSocket();
				udp.onListening(res => {
					console.log('正在监听...');
				})
				const password = this.password;
				const ssid = this.ssid;


				let port = udp.bind(60156);
				let message = JSON.stringify({
					port,
					password,
					ssid
				});

				let isConnect = false;
				console.log('port', port);

				// for (var i = 0; i < 3; i++) {
				// 	udp.send({
				// 		address: '192.168.4.1',
				// 		port: 42254,
				// 		message
				// 	});
				// 	console.log(i)
				// }
				// console.log(message);
				udp.onMessage((res) => {
					//字符串转换，很重要
					let unit8Arr = new Uint8Array(res.message);
					let encodedString = String.fromCharCode.apply(null, unit8Arr);
					let dat = decodeURIComponent(escape((encodedString)));

					let str = JSON.parse(dat);

					isConnect = true;
					console.log("第一次data:", str);
					switch (str.code) {
						//成功收到信息
						case 0:
							this.steps[0].success = true;
							udp.send({
								address: '255.255.255.255',
								port: 42254,
								message
							});

							break;
							//成功解析到信息
						case 1:
							this.steps[1].success = true;
							udp.send({
								address: '255.255.255.255',
								port: 42254,
								message: 'I GOT YOU'
							});


							// wx.stopWifi();
							udp.offListening();
							udp.offMessage();
							udp.offClose();
							udp.close();
							// that.startWifi();
							wx.connectWifi({
								SSID: ssid,
								password: password,
								success: () => {},
								fail() {
									// uni.showToast({
									// 	title: 'wifi连接失败',
									// 	icon: 'error'
									// })
								}
							});
							wx.onWifiConnected((result) => {
								console.log('重连wifi', result)
								that.steps[2].success = true;

								// setTimeout(() => {
								// 	that.steps[3].success = true;
								// 	uni.setStorageSync('isCreated', true);
								// 	setTimeout(() => {
								// 		uni.switchTab({
								// 			url: '../index/index'
								// 		})
								// 	}, 1000)

								// }, 6000)

								const newUdp = wx.createUDPSocket();

								const newPort = newUdp.bind(60156);
								var isCreated = false;
								newUdp.onListening(res => {
									console.log('再次监听中。。。');
								});
								var flag = true;
								var deviceCreateInfo;
								newUdp.onMessage(async re => {
									let _unit8Arr = new Uint8Array(re.message);
									let _encodedString = String.fromCharCode
										.apply(null, _unit8Arr);
									let _dat = decodeURIComponent(escape((
										_encodedString)));

									let _data = JSON.parse(_dat);



									let deviceId = null;

									console.log("第二次data:", _data);
									switch (_data.code) {
										case 2:
											var MasterKey = '8864744d63f64057847a2db490e49972';
											if (flag) {
												deviceCreateInfo = await request(
													'/aep_device_management/device',
													'POST', 20181031202117, {
														MasterKey
													}, {
														productId: parseInt(_data.data
															.productId),
														deviceName: '空气盒子',
														deviceSn: 'device123456',
														operator: _data.data.operator
													});
												console.log('设备创建结果：', deviceCreateInfo)
												that.steps[3].success = true;
												deviceId = deviceCreateInfo.data.result
													.deviceId;
												let message2 = {
													port: newPort,
													deivceId: deviceCreateInfo.data.result
														.deviceId,
													token: deviceCreateInfo.data.result
														.token
												};


												console.log('message2:', message2)
												console.log('flag：', flag)
												flag = false;
											}
											newUdp.send({
												address: '255.255.255.255',
												port: 42254,
												message: message2
											});
											break;
										case 3:
											newUdp.offListening();
											newUdp.offMessage();
											newUdp.offClose();
											newUdp.close();

											let count = 0;
											var timer2 = setInterval(async () => {
												count++;
												if (count > 5) {
													clearInterval(timer2);
												};
												const theDeviceData =
													await request(
														'/aep_device_management/device',
														'GET',
														20181031202139, {
															MasterKey,
															deviceId,
															productId: 15083491
														});
												if ((count <= 5) && (theDeviceData
														.result.netStatus === 1)) {
													that.steps[4].success = true;
													isCreated = true;
													clearInterval(timer2)
													uni.switchTab({
														url: '../index/index'
													})
												};
											}, 500);

											break;
									}

								});

								var timer3 = setTimeout(() => {
									if (!isCreated) {
										uni.showToast({
											title: '绑定失败',
											icon: 'error'
										})

										newUdp.offListening();
										newUdp.offMessage();
										newUdp.offClose();
										newUdp.close();

										this.activeTop = 1;
									}

									clearTimeout(timer3);
								}, 30 * 1000)
							});
							break;
					}
				});


				timer = setTimeout(() => {
					if (!isConnect) {
						uni.showToast({
							icon: 'error',
							title: '通信失败'
						});
						udp.offListening();
						udp.offMessage();
						udp.offClose();
						udp.close();

						that.activeTop = 1;

					}

					clearTimeout(timer);
				}, 30 * 1000);


				//#endif
			},


		}
	}
</script>

<style>
	.form {
		width: 80vw;
		margin: 0 auto;
	}

	.title {
		font-size: 38rpx;
	}

	label {
		display: flex;
		align-items: center;
		padding: 35rpx 0;
		border-bottom: 2rpx solid #bfbfbf;
	}

	.icon {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	input {
		padding: 15rpx 30rpx;
		flex: 1
	}

	.btn {
		width: 80%;
		margin: 30rpx auto;
	}

	.teach {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0 0 30rpx 0;
	}

	.step {
		margin: 30rpx auto;
		width: 50%;
	}

	.item {
		display: flex;
		align-items: center;
		margin: 15rpx 0;
	}

	.item>image {
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
	}

	.desc {
		padding: 0 15rpx;
	}
</style>
